import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getToken } from '@/utils/auth'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:9000',
  timeout: 30000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const appStore = useAppStore()
    
    // 显示加载状态
    if (config.showLoading !== false) {
      appStore.setLoading(true)
    }
    
    // 添加认证token
    const token = getToken()
    if (token) {
      // 用户已登录，添加认证头
      config.headers.Authorization = `Bearer ${token}`
      
      // 如果是访问用户服务API，添加额外的Cookie认证方式
      if (config.url && config.url.includes('/api/zenithMind/user')) {
        // 在cookie中也设置token
        document.cookie = `Authorization=Bearer ${token}; path=/; samesite=strict`;
      }
    }
    
    // 添加请求ID用于追踪
    config.headers['X-Request-ID'] = generateRequestId()
    
    // 添加时间戳防止缓存
    if (config.method === 'get' && config.preventCache !== false) {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    // 处理文件上传
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    
    console.log('请求发送:', {
      url: config.url,
      method: config.method,
      params: config.params,
      data: config.data,
      headers: {
        Authorization: config.headers.Authorization ? '已设置' : '未设置'
      }
    })
    
    return config
  },
  error => {
    const appStore = useAppStore()
    appStore.setLoading(false)
    console.error('请求配置错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const appStore = useAppStore()
    appStore.setLoading(false)
    
    const { data, config } = response
    
    console.log('响应接收:', {
      url: config.url,
      status: response.status,
      data: data
    })
    
    // 处理不同的响应格式
    if (data.code !== undefined) {
      // 标准响应格式 { code, message, data }
      if (data.code === 200 || data.code === 0) {
        // 成功响应
        if (config.showSuccessMessage && data.message) {
          ElMessage.success(data.message)
        }
        return data
      } else if (data.code === 401) {
        // 未授权，需要重新登录
        handleUnauthorized()
        return Promise.reject(new Error(data.message || '未授权访问'))
      } else if (data.code === 403) {
        // 权限不足
        ElMessage.error(data.message || '权限不足')
        return Promise.reject(new Error(data.message || '权限不足'))
      } else {
        // 其他错误
        const errorMessage = data.message || '请求失败'
        if (config.showErrorMessage !== false) {
          ElMessage.error(errorMessage)
        }
        return Promise.reject(new Error(errorMessage))
      }
    } else {
      // 直接返回数据
      return data
    }
  },
  error => {
    const appStore = useAppStore()
    appStore.setLoading(false)
    
    console.error('响应错误:', error)
    
    let message = '网络错误'
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          message = data.message || '请求参数错误'
          break
        case 401:
          message = '未授权访问'
          handleUnauthorized()
          break
        case 403:
          message = '权限不足'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网关超时'
          break
        default:
          message = data.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        message = '请求超时，请稍后重试'
      } else if (error.code === 'ERR_NETWORK') {
        message = '网络连接失败，请检查网络'
      } else {
        message = '网络错误，请稍后重试'
      }
    }
    
    // 显示错误消息
    if (error.config?.showErrorMessage !== false) {
      ElMessage.error(message)
    }
    
    return Promise.reject(error)
  }
)

// 处理未授权访问
const handleUnauthorized = () => {
  const userStore = useUserStore()
  
  ElMessageBox.confirm(
    '登录状态已过期，请重新登录',
    '系统提示',
    {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    userStore.logout().then(() => {
      router.push('/login')
    })
  }).catch(() => {
    // 用户取消，不做处理
  })
}

// 生成请求ID
const generateRequestId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 请求方法封装
export const request = {
  get(url, params = {}, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      ...config
    })
  },
  
  post(url, data = {}, config = {}) {
    return service({
      method: 'post',
      url,
      data,
      ...config
    })
  },
  
  put(url, data = {}, config = {}) {
    return service({
      method: 'put',
      url,
      data,
      ...config
    })
  },
  
  delete(url, config = {}) {
    return service({
      method: 'delete',
      url,
      ...config
    })
  },
  
  patch(url, data = {}, config = {}) {
    return service({
      method: 'patch',
      url,
      data,
      ...config
    })
  },
  
  upload(url, file, config = {}) {
    const formData = new FormData()
    formData.append('file', file)
    
    return service({
      method: 'post',
      url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    })
  },
  
  download(url, params = {}, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      responseType: 'blob',
      ...config
    })
  }
}

export default service
